package com.sdy.sso.provider;

import com.sdy.auth.client.config.SsoConfig;
import com.sdy.common.model.Response;
import com.sdy.common.model.Result;
import com.sdy.common.utils.DateUtil;
import com.sdy.common.utils.EncodeUtil;
import com.sdy.mq.service.MqProducerService;
import com.sdy.mvc.annotation.RemoteService;
import com.sdy.redis.service.RedisService;
import com.sdy.auth.api.AuthApi;
import com.sdy.sso.api.SsoApi;
import com.sdy.auth.api.model.UserInfo;
import com.sdy.sso.biz.constants.MqConstants;
import com.sdy.sso.biz.constants.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.security.KeyPair;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RemoteService
public class SsoProvider implements SsoApi {
    @Autowired
    private AuthApi authApi;
    @Autowired
    private RedisService redisService;
    @Autowired
    private MqProducerService mqProducerService;
    
    @PostConstruct
    public void f() {
        int a =1;
    }

    @Override
    public Response<String> login(String username, String password, String loginToken, String appCode, String ip) throws Exception {
        Result<UserInfo> result = authApi.login(
                username,
                null,
                password,
                loginToken,
                ip
        );
        if (!result.getSuccess()) {
            return Response.error(result.getMessage(), result.getCode());
        }
        String token = UUID.randomUUID().toString();
        UserInfo userInfo = result.getData();
        redisService.set(token, userInfo, SsoConfig.SESSION_SECOND_OUT);
        mqProducerService.send(MqConstants.Tags.TAG_OP_LOG,
                "0".concat(MqConstants.SEP_TOKEN)
                        .concat(userInfo.getUserId().toString()).concat(MqConstants.SEP_TOKEN)
                        .concat(DateUtil.formatTime(new Date())).concat(MqConstants.SEP_TOKEN)
                        .concat(ip).concat(MqConstants.SEP_TOKEN)
                        .concat(userInfo.getUserName() + " 登录系统：" + appCode)
        );
        KeyPair keyPair = EncodeUtil.rsaGenKeyPair();
        byte[] encryptedBytes=EncodeUtil.rsaEncrypt(token.getBytes(), keyPair.getPublic());
        String base64Token = EncodeUtil.bytesToHexString(encryptedBytes);
        redisService.set(RedisConstants.REDIS_PREFIX + "privateKey_:" + EncodeUtil.md5(base64Token).substring(20),
                Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()), 20);
        return Response.success("123123");
    }
}
